<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Auth\User;
use App\Models\Permission\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function login(Request $request) {
        $username = $request->input('username');
        $password = $request->input('password');

        $user = User::where('username', $username)->first();
        if ($user && Hash::check($password, $user->password)) {
            $user->accessTokens()->delete();
            $token = $user->createToken('btsc-rsms-user')->accessToken;

            return response()->json($token);
        }
        return response()->json(false);
    }

    public function logout(Request $request) {
        $user = $request->user();
        $user->accessTokens()->delete();
        return response()->json([
            'message' => 'Successfully logout',
        ], 200);
    }

    public function loggedUser(Request $request) {
        $user = $request->user();
        return response()->json($user);
    }

    public function loggedUserPermission(Request $request) {
        $user = $request->user();
        $permissions = $user->roles->map(function (Role $role) {
            return $role->permissions;
        })->flatten()->unique()->all();
        return response()->json($permissions);
    }
}
